package com.yun.controller;

import com.yun.pojo.Admin;
import com.yun.pojo.User;
import com.yun.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/admin")
public class AdminController {
	@Autowired
	private AdminService adminService;

	@RequestMapping("/adminList")
	public String showlist(HttpServletRequest request) {
		String name = request.getParameter("username");
		System.out.println("username" + name);
		if (name != null) {
			List<User> ulist = new ArrayList<User>();
			User user = adminService.getAdminByName(name);
			ulist.add(user);
			if (ulist != null) {
				HttpSession session1 = request.getSession();
				session1.setAttribute("ulist", ulist);
			}
			return "admin";
		} else {
			List<User> ulist = new ArrayList<User>();
			ulist = adminService.selectAll();
			if (ulist != null) {
				HttpSession session1 = request.getSession();
				session1.setAttribute("ulist", ulist);
			}
			return "admin";
		}
	}

	@RequestMapping("/adminLogin")
	public String login(HttpServletRequest request, Admin admin) {
		Admin exsitadmin = adminService.findAdmin(admin);
		if (exsitadmin != null) {
			HttpSession session = request.getSession();
			session.setAttribute(Admin.NAMESPACE, exsitadmin.getName());
			return "redirect:/admin/adminList.action";
		} else {
			request.setAttribute("msg", "用户名或密码错误");
			return "adminLogin";
		}
	}

	@RequestMapping("/deleteUser")
	@ResponseBody
	public void deleteuser(HttpServletRequest request, String username, HttpServletResponse response) {
		String name = request.getParameter("username");
		System.out.println("fhjsa" + name);
		int rows = adminService.deleteUser(name);
		if (rows > 0) {
			try {
				response.sendRedirect(request.getContextPath() + "/admin/adminList.action");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
